#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/fcntl.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include <pthread.h>
#include<net/if.h>
#include<sys/ioctl.h>
void *client(void *arg)
{    
    int fd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    struct sockaddr_in peeraddr;
    bzero(&peeraddr,sizeof(peeraddr));
    // int val;
    // int len=sizeof(val);
    // int on=1;
    // setsockopt(fd,SOL_SOCKET,SO_BROADCAST,&on,sizeof(on));
    // struct ifreq ifr;

    peeraddr.sin_family=AF_INET;
    peeraddr.sin_addr.s_addr=inet_addr("192.168.11.234");
    peeraddr.sin_port=htons(60001);
    printf("对方的:%hu\n",peeraddr.sin_port);
    char buf[100];
    while(1)
    {
        printf("开始发送\n");
        bzero(buf,100);
        fgets(buf,100,stdin);
        sendto(fd,buf,100,0,(struct sockaddr *)&peeraddr,sizeof(peeraddr));
    }

}
int main(int argc, char const *argv[])
{
    pthread_t tid;
    pthread_create(&tid, NULL, client, NULL);

    int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    struct sockaddr_in myaddr;
    bzero(&myaddr, sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    myaddr.sin_port = htons(60001);
    bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr));
    char buf[100];
    struct sockaddr_in peeraddr;
    socklen_t len = sizeof(peeraddr);
    printf("自己的:%hu\n", myaddr.sin_port);
    while (1)
    {
        printf("开始接收\n");
        bzero(buf, 100);
        bzero(&peeraddr, sizeof(peeraddr));
        recvfrom(fd, buf, 100, 0, (struct sockaddr *)&peeraddr, &len);
        fprintf(stderr, "收到[%s:%hu]的数据:%s", inet_ntoa(peeraddr.sin_addr), peeraddr.sin_port, buf);
    }

    return 0;
}